package com.central.user.controller

import cn.hutool.http.HttpRequest
import cn.hutool.json.JSONObject
import com.central.common.feign.WxService
import com.central.common.model.*
import com.central.user.service.ISysUserService
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.apache.logging.log4j.util.Base64Util
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

/**
 * @author  fly
 * @date  2021/5/26 18:12
 * @version 1.0
 */
@Api("微信授权登录")
@RequestMapping("/auth")
@RestController
open class WxLoginController {


    @Autowired
    private lateinit var wxService: WxService

    @Autowired
    private lateinit var userService: ISysUserService

    @PostMapping("/wxLogin")
    @ApiOperation("微信授权登录")
    open fun login(wxLoginParam: WxLoginParam): CommonResult<Oauth2TokenDto> =  wxService.login(wxLoginParam.code!!)?.run {
        val openId = this
        //2. 通过openId 判断用户在不在
        userService.findByOpenId(openId)?.run { success(getToken(openId)) }
            ?: kotlin.run {
                if (userService.save(SysUser().apply {
                        nickname = wxLoginParam.nickName
                        sex = wxLoginParam.gender?.toInt()
                        headImgUrl = wxLoginParam.avatarUrl
                        username = wxLoginParam.nickName
                        this.openId = openId
                        enabled = true
                        type = "wx"
                    })) success(getToken(openId)) else failed("添加用户失败")
            }
    } ?: failed("登录授权失败")


    private fun getToken(openId: String): Oauth2TokenDto = HttpRequest.post("http://121.4.149.47:9900/api-uaa/oauth/token?grant_type=openId&openId=$openId")
        .header("Authorization", "Basic ${Base64Util.encode("webApp:webApp")}")
        .executeAsync()
        .body().run {
            val result = JSONObject(this)
            com.alibaba.fastjson.JSONObject.parseObject(result.getStr("datas"), Oauth2TokenDto::class.java)
        }
}